package mx.netbrain.converter;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import mx.netbrain.dao.StorageDao;
import mx.netbrain.dao.impl.StorageDaoImpl;
import mx.netbrain.model.Storage;

public class StorageConverter implements Converter {

	public static List<Storage> storageDB;

	static {
		StorageDao storageDao = new StorageDaoImpl();
		storageDB = new ArrayList<Storage>();
		storageDB = storageDao.listAll();
	}

	@Override
	public Object getAsObject(FacesContext facesContext, UIComponent component,
			String submittedValue) {
		if (submittedValue.trim().equals("")) {
			return null;
		} else {
			try {
				Integer number = Integer.parseInt(submittedValue);
				for (Storage s : storageDB) {
					if (number.equals(s.getId())) {
						return s;
					}
				}
			} catch (NumberFormatException exception) {
				throw new ConverterException(new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Error de conversion",
						"Numero no valido"));
			}
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext facesContext, UIComponent component,
			Object value) {
		if (value == null || value.equals("")) {
			return "";
		} else {
			return String.valueOf(((Storage) value).getId());
		}
	}
}
